#include "sr.h"

static int state;
static int count;

#define READY 1
#define RUNNING 2

void
initCheckAlfa(void) {
    state = READY;
    count = 0;
}

void
checkAlfaFire(double alfa, int hasEventFlags, int *craneKnownFlags, 
        int *cranePresentFlags) {

    if(state == RUNNING) {
        if(GET_BIT(hasEventFlags, ALFABIT)) {
            if(alfa >= 0.10 || alfa <= -0.10) {
                count++;
            }
            else {
                count = 0;
            }

            if(count == 25) {
                SET_BIT_TRUE(*craneKnownFlags, EMMODECHECKALFABIT);
                SET_BIT_TRUE(*cranePresentFlags, EMMODECHECKALFABIT);
                initCheckAlfa();
            }
        }
    }

    if(!GET_BIT(*craneKnownFlags, EMMODECHECKALFABIT)) {
        SET_BIT_TRUE(*craneKnownFlags, EMMODECHECKALFABIT);
    }
}

void
checkAlfaPostfire(int hasEventFlags, int craneKnownFlags, int cranePresentFlags) {

    switch(state) {
        case READY : {
            if(GET_BIT(craneKnownFlags, TRIGGERBIT) && 
                    !GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                state = RUNNING;
            }
        } break;

        case RUNNING: {
            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                initCheckAlfa();
                break;
            }

            if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                if(GET_BIT(cranePresentFlags, EMSTOPMERGERBIT)) {
                    initCheckAlfa();
                }
            }
        } break;
    }
}
